﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using FanaticRock.AudioManage.Models;
using TagLib;

namespace FanaticRock.AudioManage.Helpers
{
    public static class AudioFormatHelper
    {
        public static SongMetadata GetMetadata(string path)
        {
            //TagLib.Id3v2.

            return new SongMetadata(path);
        }

        public static byte[] TryGetCover(Uri uri)
        {
            if (uri == null) return null;
            return TryGetCover(uri.LocalPath);
        }

        public static byte[] TryGetCover(string path)
        {
            var file = default(TagLib.File);
            try
            {
                if (System.IO.File.Exists(path) == false) return null;
                file = TagLib.File.Create(path);
                var tag = file.Tag;
                var coverBytes = GetCover(file);
                return coverBytes;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                file?.Dispose();
            }

        }


        public static byte[] GetCover(Uri uri)
        {
            if (uri == null) return null;
            return GetCover(uri.LocalPath);
        }

        public static byte[] GetCover(string path)
        {
            if (System.IO.File.Exists(path) == false) return null;
            using var file = TagLib.File.Create(path);
            var tag = file.Tag;
            var coverBytes = GetCover(file);
            return coverBytes;
        }

        public static byte[] GetCover(TagLib.File file)
        {
            if (file == null) return null;
            var picture = file.Tag.Pictures.FirstOrDefault();
            if (picture == null) return null;
            var byteVector = picture.Data;
            if (byteVector == null) return null;
            var sourceBytes = byteVector.Data;
            if (sourceBytes == null) return null;
            var copiedBytes = new byte[sourceBytes.Length];
            Array.Copy(sourceBytes, copiedBytes, sourceBytes.Length);
            return copiedBytes;
        }

        public static void SetCover(Uri uri, byte[] bytes)
        {
            if (uri == null) return;
            SetCover(uri.LocalPath, bytes);
        }

        public static void SetCover(string path, byte[] bytes)
        {
            using var file = TagLib.File.Create(path);
            SetCover(file, bytes);
        }

        public static void SetCover(TagLib.File file, byte[] bytes)
        {
            var picture = new TagLib.Picture();
            picture.Data = bytes;
            picture.MimeType = System.Net.Mime.MediaTypeNames.Image.Png;
            file.Tag.Pictures = new[] { picture };
            file.Save();
        }
    }
}
